/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * sschaffe
 *
 * File Info:
 * User: sschaffe
 * Date: 2011/01/18
 * Time: 13:06
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.core.services.sesame;

import kiwi.core.api.sesame.SesameIndexingService;
import kiwi.core.api.transaction.TransactionData;
import kiwi.core.api.triplestore.TripleStore;
import kiwi.core.model.rdf.KiWiNamespace;
import kiwi.core.model.rdf.KiWiTriple;
import kiwi.core.qualifiers.event.transaction.AfterCommit;
import org.openrdf.model.Statement;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.slf4j.Logger;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

/**
 * Add file description here!
 * <p/>
 * User: sschaffe
 */
@Named("kiwi.core.sesameIndexingService")
@ApplicationScoped
public class SesameIndexingServiceImpl implements SesameIndexingService {

    @Inject
    private Logger log;


    @Inject
    private Repository repository;


    @Inject
    private TripleStore tripleStore;


    /**
     * Apply the updates that are contained in the transaction data to the sesame triple store managed by the indexer.
     * The method is implemented as an observer of the @AfterCommit event and thus performs the indexing when
     * changes to resources, triples and namespaces in the master database have been persisted already.
     *
     * @param data
     */
    @Override
    public void updateIndex(@Observes @AfterCommit TransactionData data) {

        if(data.getAddedTriples().size() + data.getRemovedTriples().size() + data.getAddedNS().size() + data.getRemovedNS().size() > 0) {

            try {
                RepositoryConnection con = repository.getConnection();
                con.setAutoCommit(false);

                // process removals
                for(KiWiTriple triple : data.getRemovedTriples()) {
                    con.remove(KiWiSesameUtil.transformKiWiToSesame(repository,triple));
                }
                for(KiWiNamespace namespace : data.getRemovedNS()) {
                    con.removeNamespace(namespace.getUri());
                }


                // process additions
                for(KiWiTriple triple : data.getAddedTriples()) {
                    con.add(KiWiSesameUtil.transformKiWiToSesame(repository,triple));
                }
                for(KiWiNamespace namespace : data.getAddedNS()) {
                    con.setNamespace(namespace.getUri(),namespace.getPrefix());
                }

                RepositoryResult r = con.getStatements(null,null,null,true);
                List<Statement> l = r.asList();


                con.commit();
                con.close();

            } catch (RepositoryException e) {
                log.error("error while processing index update; index is not synchronized, reindexing required",e);
            }
        }

     }

    /**
     * Rebuild the Sesame index from scratch, using the currently visible triples in the triple store.
     */
    @Override
    public void rebuildIndex() {
        RepositoryConnection con = null;
        try {
            log.info("reindexing triples from database");

            long start = System.currentTimeMillis();

            con = repository.getConnection();
            con.setAutoCommit(false);

            con.clear();
            con.clearNamespaces();
            con.commit();

            for(KiWiTriple triple : tripleStore.listTriples(true)) {
                con.add(KiWiSesameUtil.transformKiWiToSesame(repository,triple));
            }

            for(KiWiNamespace namespace : tripleStore.listNamespaces()) {
                con.setNamespace(namespace.getUri(),namespace.getPrefix());
            }
            con.commit();
            con.close();

            log.info("reindexing finished after {}ms",System.currentTimeMillis()-start);
        } catch (RepositoryException e) {
            log.error("error while reindexing Sesame repository",e);
        }
    }
}
